<template>
  <div class="login-container">
    <div class="login-wrap">
      <div class="logo-wrap">
        <img class="logo" src="@/assets/imgs/logo-myzx-text.png" alt="">
        <h1>管理员登录</h1>
      </div>
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
        label-width="70px" class="demo-ruleForm">
        <el-form-item prop="username">
          <el-input placeholder="请输入账号" v-model="ruleForm.username" autocomplete="off">
            <template #prepend>
              <el-icon size="18">
                <Avatar />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input placeholder="请输入密码" v-model="ruleForm.password" type="password" autocomplete="off">
            <template #prepend>
              <el-icon size="18">
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button round size="large" class="btn-login" type="primary" @click="submitForm(ruleFormRef)">
            立即登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>

</template>

<script lang="ts" setup>

import {addRoutes} from '../router'
import { ElMessage } from 'element-plus';
import { login } from '../utils/api'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const ruleFormRef = ref(null)

const ruleForm = reactive({
  username: 'admin',
  password: '123123'
})

const rules = reactive({
  username: [{ required: true, message: "请输入账号", trigger: 'blur' }],
  password: [{ required: true, message: "请输入密码", trigger: 'blur' }],
})

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      const { data } = await login(ruleForm)
      if (data.code === 200) {
        ElMessage.success(data.msg)
        localStorage.setItem('adminLoginInfo', JSON.stringify(data.data))
        // 动态注册路由规则
        addRoutes()
        router.replace('/home')
        return false;
      }
      ElMessage.error(data.msg)
    } else {
      console.log('error submit!')
    }
  })
}

</script>

<style scoped lang="scss">
.login-container {
  position: relative;
  min-width: 1200px;
  height: 100vh;
  background-color: rgba(0, 0, 0, .9);

  .login-wrap {
    width: 400px;
    // min-height: 240px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #FFF;
    border-radius: 10px;
    padding: 20px;

    .btn-login {
      width: 100%;
    }

    .logo-wrap {
      position: relative;
      text-align: center;
      margin: 20px 0;

      .logo {
        position: absolute;
        top: -10px;
        right: 40px;
        height: 30px;
      }
    }
  }
}
</style>